﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace SmartPowerHub.Communication.Modbus
{
    public abstract class ModbusBase
    {
        protected readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
        protected readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

        public ModbusType ModbusType { get; protected set; }
        public abstract Task ConnectAsync();

        public abstract Task DisconnectAsync();

        public virtual void Dispose()
        {
            DisconnectAsync();
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource.Dispose();
            _sendLock.Dispose();
        }

        /// <summary>
        /// 发送读取数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="functionCode"></param>
        /// <param name="address"></param>
        /// <param name="count"></param>
        /// <param name="slaveAddress"></param>
        /// <returns></returns>
        protected abstract Task<ModbusResponse<T>> SendReadRequestWithReceiveAsync<T>(FunctionCode functionCode, ushort address, ushort count, byte slaveAddressOrUnitId = 0x01);
        /// <summary>
        /// 发送写入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="functionCode"></param>
        /// <param name="address"></param>
        /// <param name="values"></param>
        /// <param name="slaveAddress"></param>
        /// <returns></returns>
        protected abstract Task<ModbusResponse> SendWriteRequestWithReceiveAsync<T>(FunctionCode functionCode, ushort address, T[] values, byte slaveAddressOrUnitId = 0x01);
    }
}
